import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/loading_dialog.dart';
import 'pushup_screen.dart';
import 'pullup_screen.dart';
import 'squat_screen.dart';
import 'plank_screen.dart';
import '../services/database_service.dart';

class SportScreen extends StatefulWidget {
  const SportScreen({Key? key}) : super(key: key);

  @override
  State<SportScreen> createState() => _SportScreenState();
}

class _SportScreenState extends State<SportScreen> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  final _databaseService = DatabaseService();
  Map<String, Map<String, int>> _dayRecords = {};
  int _restTimeSeconds = 60; // 默认60秒组间休息

  @override
  void initState() {
    super.initState();
    _loadAllRecords();
    _loadRestTimeSetting();
  }

  Future<void> _loadRestTimeSetting() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _restTimeSeconds = prefs.getInt('sport_rest_time') ?? 60;
    });
  }

  Future<void> _saveRestTimeSetting(int seconds) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('sport_rest_time', seconds);
    setState(() {
      _restTimeSeconds = seconds;
    });
  }

  Future<void> _loadAllRecords() async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query('sport_records');
    final Map<String, Map<String, int>> dayMap = {};
    for (var m in maps) {
      final date = m['date'] as String;
      final type = m['type'] as String;
      final count = m['count'] as int;
      // 确保 date 对应的 map 存在，不存在就创建一个 {}
      final typeCountMap = dayMap.putIfAbsent(date, () =>  {});
      typeCountMap[type] = count;

    }
    setState(() {
      _dayRecords = dayMap;
    });
  }

  Future<bool> _onWillPop() async {
    if (await _databaseService.shouldSyncDatabase()) {
      final context = this.context;
      if (!context.mounted) return true;

      LoadingDialog.show(context);
      await DatabaseService().syncDatabase();
      if (!context.mounted) return true;

      LoadingDialog.hide(context);
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    final todayKey =
        '${_focusedDay.year.toString().padLeft(4, '0')}-${_focusedDay.month.toString().padLeft(2, '0')}-${_focusedDay.day.toString().padLeft(2, '0')}';
    final todayRecords = _dayRecords[todayKey] ?? {};
    Set<DateTime> eventDays = _dayRecords.keys.map((k) {
      final parts = k.split('-');
      return DateTime(
          int.parse(parts[0]), int.parse(parts[1]), int.parse(parts[2]));
    }).toSet();
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('运动记录'),
          actions: [
            IconButton(
              icon: const Icon(Icons.settings),
              onPressed: _showRestTimeSettings,
            ),
          ],
        ),
        body: Column(
          children: [
            TableCalendar(
              headerStyle: const HeaderStyle(
                formatButtonVisible : false,
              ),
              firstDay: DateTime.utc(2025, 5, 1),
              lastDay: DateTime.utc(2030, 12, 31),
              focusedDay: _focusedDay,
              selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
              calendarBuilders: CalendarBuilders(
                markerBuilder: (context, day, events) {
                  if (eventDays
                      .contains(DateTime(day.year, day.month, day.day))) {
                    return Positioned(
                      bottom: 4,
                      left: 0,
                      right: 0,
                      child: Center(
                        child: Container(
                          width: 8,
                          height: 8,
                          decoration: const BoxDecoration(
                            color: Colors.green,
                            shape: BoxShape.circle,
                          ),
                        ),
                      ),
                    );
                  }
                  return null;
                },
              ),
              onDaySelected: (selectedDay, focusedDay) {
                setState(() {
                  _selectedDay = selectedDay;
                  _focusedDay = focusedDay;
                });
              },
            ),
            const SizedBox(height: 16),
            if (todayRecords != null)
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('当日运动：',
                        style:
                            TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                    ...todayRecords.entries.map((entry) => Row(
                      children: [
                        const Icon(Icons.fiber_manual_record,
                            size: 10, color: Colors.green),
                        const SizedBox(width: 6),
                        Text('${entry.key} * ${entry.value}',
                            style: const TextStyle(fontSize: 15)),
                      ],
                    )),
                  ],
                ),
              ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildSportButton('上肢\n俯卧撑', Icons.fitness_center, Colors.blue),
                _buildSportButton('上肢\n引体向上', Icons.sports_martial_arts, Colors.purple),
                _buildSportButton('下肢\n深蹲', Icons.sports_gymnastics, Colors.green),
                _buildSportButton(
                    '核心\n平板支撑', Icons.accessibility_new, Colors.orange),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSportButton(String label, IconData icon, Color color) {
    return Column(
      children: [
        InkWell(
          onTap: () {
            if (label.contains('俯卧撑')) {
              Navigator.push(context,
                      MaterialPageRoute(builder: (_) => const PushUpScreen()))
                  .then((_) => _loadAllRecords());
            } else if (label.contains('引体向上')) {
              Navigator.push(context,
                      MaterialPageRoute(builder: (_) => const PullUpScreen()))
                  .then((_) => _loadAllRecords());
            } else if (label.contains('深蹲')) {
              Navigator.push(context,
                      MaterialPageRoute(builder: (_) => const SquatScreen()))
                  .then((_) => _loadAllRecords());
            } else if (label.contains('平板支撑')) {
              Navigator.push(context,
                      MaterialPageRoute(builder: (_) => const PlankScreen()))
                  .then((_) => _loadAllRecords());
            }
          },
          borderRadius: BorderRadius.circular(32),
          child: Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: color.withOpacity(0.15),
              borderRadius: BorderRadius.circular(32),
            ),
            child: Icon(icon, color: color, size: 36),
          ),
        ),
        const SizedBox(height: 8),
        Text(label,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
      ],
    );
  }

  void _showRestTimeSettings() {
    int tempRestTime = _restTimeSeconds;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('设置组间休息时间'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('当前设置：$_restTimeSeconds 秒'),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      _buildTimeButton(30, tempRestTime, (time) {
                        Logger().d("click");
                        setState(() => tempRestTime = time);
                      }),
                      _buildTimeButton(45, tempRestTime, (time) {
                        setState(() => tempRestTime = time);
                      }),
                      _buildTimeButton(60, tempRestTime, (time) {
                        setState(() => tempRestTime = time);
                      }),
                    ],
                  ),
                  const SizedBox(height: 16),
                  const Text('自定义时间（秒）：'),
                  const SizedBox(height: 8),
                  SizedBox(
                    width: 100,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      textAlign: TextAlign.center,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: '60',
                      ),
                      onChanged: (value) {
                        final int? customTime = int.tryParse(value);
                        if (customTime != null && customTime > 0 && customTime <= 300) {
                          setState(() => tempRestTime = customTime);
                        }
                      },
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    _saveRestTimeSetting(tempRestTime);
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildTimeButton(int seconds, int currentSelection, Function(int) onSelect) {
    return GestureDetector(
      onTap: () {
        onSelect(seconds);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: currentSelection == seconds ? Colors.blue : Colors.grey[200],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Text(
          '${seconds}s',
          style: TextStyle(
            color: currentSelection == seconds ? Colors.white : Colors.black,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
